package org.aplikator.server;

import org.aplikator.client.shared.descriptor.EntityDTO;
import org.aplikator.server.descriptor.Application;
import org.aplikator.server.persistence.search.SearchFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@SuppressWarnings("serial")
public class ApplicationLoaderServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        boolean updateDB = Boolean.parseBoolean(req.getParameter("update"));
        boolean checkDB = Boolean.parseBoolean(req.getParameter("check"));
        boolean reindex = Boolean.parseBoolean(req.getParameter("reindex"));
        if (reindex) {
        	String entityName = req.getParameter("entity");
        	EntityDTO entity = new EntityDTO(entityName,entityName);
        	SearchFactory.get().index(entity);
        } else {
            resp.getOutputStream().write(Application.get().generateDDL(updateDB, checkDB).getBytes());
        }
        resp.getOutputStream().close();
            
    }

}
